package com.nd.config;

import com.nd.realm.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CustomAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> realms = this.getRealms();
        //对realm进行分发
        System.out.println(authenticationToken);
        MallToken mallToken = (MallToken) authenticationToken;
        String type = mallToken.getType();
        List<Realm> realmList = new ArrayList<>();
        for (Realm realm : realms) {
            if (realm.getName().toLowerCase().contains(type)) {
                realmList.add(realm);
            }
        }
        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realmList.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
